package net.borderwars.io;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * Source code from "Java Distributed Computing", by Jim Farley.
 * <p/>
 * Class: RTInputStream
 * Example: 8-2
 * Description: An input stream that monitors its own "real time"
 * data throughput.
 */

public class RTInputStream extends FilterInputStream {
    DataMonitor monitor;

    public RTInputStream (InputStream in) {
        super (in);
        monitor = new DataMonitor ();
    }

    public int read () throws IOException {
        Date start = new Date ();
        int b = super.read ();
        monitor.addSample (1, start, new Date ());
        return b;
    }

    public int read (byte data[]) throws IOException {
        Date start = new Date ();
        int cnt = super.read (data);
        monitor.addSample (cnt, start, new Date ());
        return cnt;
    }

    public int read (byte data[], int off, int len)
            throws IOException {
        Date start = new Date ();
        int cnt = super.read (data, off, len);
        monitor.addSample (cnt, start, new Date ());
        return cnt;
    }

    public float averageRate () {
        return monitor.getAverageRate ();
    }

    public float lastRate () {
        return monitor.getLastRate ();
    }
}